package cn.seven._conf._fastjson;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.jfinal.plugin.activerecord.Record;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * create by 张天笑, 2017/11/14 15:02
 */
public class CustomFastJsonSerializer {

    public static FastJsonConfig config(FastJsonConfig fastJsonConfig) {
        fastJsonConfig.getSerializeConfig().put(Record.class, new JFinalRecordSerializer());

        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty);

        fastJsonConfig.setSerializeFilters(nullToEmptyFilter);
        return fastJsonConfig;
    }

    private static ValueFilter nullToEmptyFilter = new ValueFilter() {
        public Object process(Object obj, String s, Object v) {
            if (v == null)
                return "";
            return v;
        }
    };
}

class JFinalRecordSerializer implements ObjectSerializer {
    JFinalRecordSerializer() {
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object != null) {
            Record record = (Record) object;

            Map<String, Object> map = record.getColumns();
            serializer.write(map);
        }
    }
}